package com.wk.playersdk.util;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class WkThreadPoolTools
{
    private   ExecutorService singleThreadPool = null ;
    private ExecutorService getThreadPoolsIncetance()
    {
        //guava-17.0.jar
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("wk-pool-%d").build();
        RejectedExecutionHandler handler =new ThreadPoolExecutor.AbortPolicy();
        /*核心线程数量newSingleThreadExecutor
        最大线程数量ScheduledThreadPoolExecutor
        当线程池数量超过核心线程数量以后，空闲时间超过这个值的线程会被终止
        KeepAlive时间单位
        任务队列
        创建线程的工厂对象
        任务被拒绝后调用的handler*/
        ExecutorService   threadPool = new ThreadPoolExecutor(
                5 ,  10 , 3 ,  TimeUnit.MICROSECONDS ,
                new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE) ,
                threadFactory ,
                handler  ) ;
        return  threadPool ;
    }
    /**提交任务并执行*/
    public   void addTask(Runnable runnable)
    {
        if (singleThreadPool == null)
        {
            singleThreadPool= getThreadPoolsIncetance();
        }
        //运行线程池中的任务
        singleThreadPool.submit(runnable) ;
    }
    /**关闭线程池*/
    public   void shutdownThreadPool()
    {
        if (singleThreadPool != null)
        {
            if(!singleThreadPool.isShutdown())
            {
                singleThreadPool.shutdownNow() ;
            }
        }
    }
}